import React, { useState } from 'react';
import { ProForm, ProFormText, ProFormCheckbox } from '@ant-design/pro-components';
import { Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '@/stores/auth';
import './index.css';

interface LoginForm {
  username: string;
  password: string;
  remember: boolean;
}

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const { login } = useAuthStore();
  
  const from = (location.state as any)?.from?.pathname || '/dashboard';

  const onFinish = async (values: LoginForm) => {
    setLoading(true);
    try {
      await login(values.username, values.password);
      message.success('登录成功');
      navigate(from, { replace: true });
    } catch (error: any) {
      message.error(error.message || '登录失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <div className="login-content">
        <Card className="login-card">
          <div className="login-header">
            <h1>儿童闪卡CMS</h1>
            <p>管理后台系统</p>
          </div>
          
          <ProForm
            name="login"
            size="large"
            onFinish={onFinish}
            autoComplete="off"
            initialValues={{ remember: true }}
            submitter={{
              searchConfig: {
                submitText: '登录',
              },
              submitButtonProps: {
                loading,
                size: 'large',
                style: {
                  width: '100%',
                },
              },
              render: (_, dom) => dom.pop(),
            }}
          >
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined />,
                placeholder: '用户名',
              }}
              rules={[
                { required: true, message: '请输入用户名!' },
                { min: 3, message: '用户名至少3个字符!' }
              ]}
            />

            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
                placeholder: '密码',
              }}
              rules={[
                { required: true, message: '请输入密码!' },
                { min: 6, message: '密码至少6个字符!' }
              ]}
            />

            <ProFormCheckbox name="remember">
              记住登录状态
            </ProFormCheckbox>
          </ProForm>
        </Card>
      </div>
    </div>
  );
};

export default Login;